<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="118px">
      <el-form-item label="型号" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择型号" clearable>
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id + ''"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="mac" prop="mac">
        <el-input v-model="queryParams.mac" placeholder="请输入设备mac" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="imei" prop="imei">
        <el-input v-model="queryParams.imei" placeholder="请输入imei" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="所属组织" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入所属组织"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option v-for="dict in dict.type.pile_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
   <!--   <el-form-item label="电池电量" prop="batteryLevel">
        <el-input v-model="queryParams.batteryLevel" placeholder="请输入电池电量" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
<!--      <el-form-item label="最后通讯时间" prop="lastCommunication">
        <el-date-picker clearable v-model="queryParams.lastCommunication" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择最后通讯时间">
        </el-date-picker>
      </el-form-item> -->

  <!--    <el-form-item label="联网信号强度" prop="rssi">
        <el-input v-model="queryParams.rssi" placeholder="请输入联网信号强度" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="校区" prop="cellId">
        <el-select v-model="queryParams.cellId" placeholder="请选择校区" clearable @change="handleCellChange">
          <el-option
            v-for="item in cellOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋" prop="unitId">
        <el-select
          v-model="queryParams.unitId"
          placeholder="请选择楼栋"
          clearable
          @change="handleUnitChange"
          :disabled="!queryParams.cellId">
          <el-option
            v-for="item in unitOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floorId">
        <el-select
          v-model="queryParams.floorId"
          placeholder="请选择楼层"
          clearable
          @change="handleFloorChange"
          :disabled="!queryParams.unitId">
          <el-option
            v-for="item in floorOptions"
            :key="item.id"
            :label="item.floorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房间" prop="homeId">
        <el-select
          v-model="queryParams.homeId"
          placeholder="请选择房间"
          clearable
          :disabled="!queryParams.floorId">
          <el-option
            v-for="item in homeOptions"
            :key="item.id"
            :label="item.roomName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['lock:device:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['lock:device:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['lock:device:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['lock:device:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="型号" align="center" prop="type">
        <template slot-scope="scope">
          {{ getTypeName(scope.row.type) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="名称" align="center" prop="name" /> -->
      <el-table-column label="mac" align="center" prop="mac" />
      <el-table-column label="imei" align="center" prop="imei" />
      <el-table-column label="位置信息" align="center" width="280">
        <template slot-scope="scope">
          <span>{{ scope.row.cellName || '' }}-{{ scope.row.unitName || '' }}-{{ scope.row.floorName || '' }}-{{ scope.row.roomName || '' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属组织" align="center" prop="deptId" /> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <!--      <el-table-column label="固件版本" align="center" prop="firmwareVersion">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.version" :value="scope.row.firmwareVersion"/>
        </template>
      </el-table-column> -->
     <!-- <el-table-column label="设备状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_status" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column label="电池电量" align="center" prop="batteryLevel" >
        <template slot-scope="scope">
            <span>{{ scope.row.batteryLevel }}%</span>
          </template>
        </el-table-column>
      <el-table-column label="最后通讯时间" align="center" prop="lastCommunication" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.lastCommunication }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电池电压" align="center" prop="volt" />
      <el-table-column label="联网信号强度" align="center" prop="rssi" />
      <!-- <el-table-column label="心跳间隔" align="center" prop="hbinterval" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['lock:device:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['lock:device:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="型号" prop="type">
              <el-select v-model="form.type" placeholder="请选择型号">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="mac" prop="mac">
              <el-input v-model="form.mac" placeholder="请输入mac" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="校区" prop="cellId">
              <el-select v-model="form.cellId" placeholder="请选择校区" @change="handleCellChange">
                <el-option
                  v-for="item in cellOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼栋" prop="unitId">
              <el-select
                v-model="form.unitId"
                placeholder="请选择楼栋"
                @change="handleUnitChange"
                :disabled="!form.cellId">
                <el-option
                  v-for="item in unitOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorId">
              <el-select
                v-model="form.floorId"
                placeholder="请选择楼层"
                @change="handleFloorChange"
                :disabled="!form.unitId">
                <el-option
                  v-for="item in floorOptions"
                  :key="item.id"
                  :label="item.floorName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间" prop="homeId">
              <el-select
                v-model="form.homeId"
                placeholder="请选择房间"
                :disabled="!form.floorId">
                <el-option
                  v-for="item in homeOptions"
                  :key="item.id"
                  :label="item.roomName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
     <!--   <el-row>
          <el-col :span="12">
            <el-form-item label="固件版本" prop="firmwareVersion">
              <el-select v-model="form.firmwareVersion" placeholder="请选择固件版本">
                <el-option v-for="dict in dict.type.version" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row> -->
        <el-row>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <!--   <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item> -->

       <el-form-item label="imei" prop="imei">
          <el-input v-model="form.imei" placeholder="请输入imei" />
        </el-form-item>

        <!--
        <el-form-item label="所属组织" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入所属组织" />
        </el-form-item> -->

        <!--
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择设备状态">
            <el-option v-for="dict in dict.type.pile_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <!--  <el-form-item label="电池电量" prop="batteryLevel">
          <el-input v-model="form.batteryLevel" placeholder="请输入电池电量" />
        </el-form-item> -->
        <!--        <el-form-item label="最后通讯时间" prop="lastCommunication">
          <el-date-picker clearable v-model="form.lastCommunication" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择最后通讯时间">
          </el-date-picker>
        </el-form-item> -->
        <!--      <el-form-item label="电池电压" prop="volt">
          <el-input v-model="form.volt" placeholder="请输入电池电压" />
        </el-form-item>
        <el-form-item label="联网信号强度" prop="rssi">
          <el-input v-model="form.rssi" placeholder="请输入联网信号强度" />
        </el-form-item>
        <el-form-item label="心跳间隔" prop="hbinterval">
          <el-input v-model="form.hbinterval" placeholder="请输入心跳间隔" />
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listDevice,
    getDevice,
    delDevice,
    addDevice,
    updateDevice
  } from "@/api/lock/device";
  import { listCell2 } from "@/api/lock/cell";
  import { listUnit2 } from "@/api/lock/unit";
  import { listFloor2 } from "@/api/lock/floor";
  import { listHome2 } from "@/api/lock/home";
  import { listType2 } from "@/api/lock/type";

  export default {
    name: "Device",
    dicts: ['pile_type', 'device_status', 'version', 'is_flag_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 设备管理表格数据
        deviceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 级联选择数据
        cellOptions: [],
        unitOptions: [],
        floorOptions: [],
        homeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          type: null,
          name: null,
          mac: null,
          imei: null,
          cellId: null,
          unitId: null,
          floorId: null,
          homeId: null,
          deptId: null,
          firmwareVersion: null,
          status: null,
          batteryLevel: null,
          lastCommunication: null,
          volt: null,
          rssi: null,
          hbinterval: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          type: [{
            required: true,
            message: "型号不能为空",
            trigger: "change"
          }],
          mac: [{
            required: true,
            message: "设备id不能为空",
            trigger: "blur"
          }],
          cellId: [{
            required: true,
            message: "校区不能为空",
            trigger: "change"
          }],
          unitId: [{
            required: true,
            message: "楼栋不能为空",
            trigger: "change"
          }],
          floorId: [{
            required: true,
            message: "楼层不能为空",
            trigger: "change"
          }],
          homeId: [{
            required: true,
            message: "房间不能为空",
            trigger: "change"
          }],
          status: [{
            required: true,
            message: "设备状态不能为空",
            trigger: "change"
          }],

        },
        // 型号选项
        typeOptions: [],
      };
    },
    created() {
      this.getList();
      this.getCellList();
      this.getTypeList();
    },
    methods: {
      /** 查询设备管理列表 */
      getList() {
        this.loading = true;
        listDevice(this.queryParams).then(response => {
          this.deviceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 获取校区列表 */
      getCellList() {
        listCell2().then(response => {
          this.cellOptions = response.rows;
        });
      },
      /** 获取楼栋列表 */
      getUnitList(cellId) {
        listUnit2({ cellId: cellId }).then(response => {
          this.unitOptions = response.rows || [];
          if (!this.form.id) {  // 只在新增时重置
            this.form.unitId = undefined;
            this.form.floorId = undefined;
            this.form.homeId = undefined;
            this.floorOptions = [];
            this.homeOptions = [];
          }
        });
      },
      /** 获取楼层列表 */
      getFloorList(unitId) {
        listFloor2({ unitId: unitId }).then(response => {
          this.floorOptions = response.rows || [];
          if (!this.form.id) {  // 只在新增时重置
            this.form.floorId = undefined;
            this.form.homeId = undefined;
            this.homeOptions = [];
          }
        });
      },
      /** 获取房间列表 */
      getHomeList(floorId) {
        if (!floorId) {
          this.homeOptions = [];
          if (!this.form.id) {  // 只在新增时重置
            this.form.homeId = undefined;
          }
          return;
        }
        listHome2({ floorId: floorId }).then(response => {
          this.homeOptions = response.rows || [];
          if (!this.form.id && this.homeOptions.length === 0) {  // 只在新增时重置
            this.form.homeId = undefined;
          }
        });
      },
      /** 校区选择框变化 */
      handleCellChange(val) {
        if (!this.form.id) {  // 只在新增时重置
          // 清除下级选项
          this.form.unitId = undefined;
          this.form.floorId = undefined;
          this.form.homeId = undefined;
          this.unitOptions = [];
          this.floorOptions = [];
          this.homeOptions = [];
        }

        if (val) {
          this.getUnitList(val);
        }
      },
      /** 楼栋选择框变化 */
      handleUnitChange(val) {
        if (!this.form.id) {  // 只在新增时重置
          // 清除下级选项
          this.form.floorId = undefined;
          this.form.homeId = undefined;
          this.floorOptions = [];
          this.homeOptions = [];
        }

        if (val) {
          this.getFloorList(val);
        }
      },
      /** 楼层选择框变化 */
      handleFloorChange(val) {
        if (!this.form.id) {  // 只在新增时重置
          // 清除下级选项
          this.form.homeId = undefined;
          this.homeOptions = [];
        }

        if (val) {
          this.getHomeList(val);
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          type: null,
          name: null,
          mac: null,
          imei: null,
          cellId: null,
          unitId: null,
          floorId: null,
          homeId: null,
          deptId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          firmwareVersion: null,
          status: null,
          batteryLevel: null,
          lastCommunication: null,
          volt: null,
          rssi: null,
          hbinterval: null,
          isFlag: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加设备管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getDevice(id).then(response => {
          this.form = response.data;
          // 获取关联数据
          if (this.form.cellId) {
            this.getUnitList(this.form.cellId);
          }
          if (this.form.unitId) {
            this.getFloorList(this.form.unitId);
          }
          if (this.form.floorId) {
            this.getHomeList(this.form.floorId);
          }
          this.open = true;
          this.title = "修改设备管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateDevice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addDevice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除设备管理编号为"' + ids + '"的数据项？').then(function() {
          return delDevice(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('lock/device/export', {
          ...this.queryParams
        }, `device_${new Date().getTime()}.xlsx`)
      },
      /** 获取型号列表 */
      getTypeList() {
        listType2().then(response => {
          this.typeOptions = response.rows;
        });
      },
      /** 获取型号名称 */
      getTypeName(typeId) {
        if (!typeId) return '';
        const type = this.typeOptions.find(t => t.id + '' === typeId + '');
        return type ? type.name : '';
      },
    }
  };
</script>
